package cn.iocoder.yudao.framework.security.core.filter;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.core.RequestSection;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class RequestSectionFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        List<RequestSection> requestSectionList = SpringFactoriesLoader.loadFactories(RequestSection.class, Thread.currentThread().getContextClassLoader());
        if (CollectionUtil.isNotEmpty(requestSectionList)) {
            for (RequestSection requestSection : requestSectionList) {
                requestSection.begin();
            }
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            if (CollectionUtil.isNotEmpty(requestSectionList)) {
                for (RequestSection requestSection : requestSectionList) {
                    requestSection.end();
                }
            }
        }
    }
}
